package updateinfoimpl

import (
	"fmt"

	"github.com/xuri/excelize/v2"

	"cvevulner/cve-ddd/domain"
)

func (impl updateInfoImpl) GenerateCollectExcel(groupData map[string]domain.CollectedDataSlice) (ret []byte, err error) {
	excel := excelize.NewFile()

	for branch, data := range groupData {
		sheetIndex, _ := excel.NewSheet(branch)
		excel.SetActiveSheet(sheetIndex)
		if err = impl.setCollectExcelHeader(excel, branch); err != nil {
			return
		}

		for index, v := range data {
			if err = excel.SetCellValue(branch, fmt.Sprintf("A%d", index+2), v.CveNum); err != nil {
				return
			}

			if err = excel.SetCellValue(branch, fmt.Sprintf("B%d", index+2), v.Issue.Number); err != nil {
				return
			}

			if err = excel.SetCellValue(branch, fmt.Sprintf("C%d", index+2), v.Issue.Repo); err != nil {
				return
			}

			if err = excel.SetCellValue(branch, fmt.Sprintf("D%d", index+2), v.Score); err != nil {
				return
			}

			if err = excel.SetCellValue(branch, fmt.Sprintf("E%d", index+2), v.Version); err != nil {
				return
			}

			if err = excel.SetCellValue(branch, fmt.Sprintf("F%d", index+2), "否"); err != nil {
				return
			}
		}
	}

	buff, err := excel.WriteToBuffer()
	if err != nil {
		return
	}

	return buff.Bytes(), nil
}

func (impl updateInfoImpl) setCollectExcelHeader(f *excelize.File, branch string) error {
	if err := f.SetCellValue(branch, "A1", "cve编号"); err != nil {
		return err
	}
	if err := f.SetCellValue(branch, "B1", "issue编号"); err != nil {
		return err
	}
	if err := f.SetCellValue(branch, "C1", "issue所属仓库"); err != nil {
		return err
	}
	if err := f.SetCellValue(branch, "D1", "score"); err != nil {
		return err
	}
	if err := f.SetCellValue(branch, "E1", "version"); err != nil {
		return err
	}
	if err := f.SetCellValue(branch, "F1", "abi是否变化"); err != nil {
		return err
	}

	return nil
}
